package org.xxpay.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.entity.SysAttachment;
import org.xxpay.core.entity.SysAttachmentExample;
import org.xxpay.core.service.ISysAttachmentService;
import org.xxpay.service.dao.mapper.SysAttachmentMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysAttachmentServiceImpl implements ISysAttachmentService {

    @Autowired
    private SysAttachmentMapper recordMapper;

    @Override
    public List<SysAttachment> findByInfo(Long infoId, Byte infoType) {

        SysAttachmentExample exa = new SysAttachmentExample();
        exa.createCriteria().andInfoIdEqualTo(infoId).andInfoTypeEqualTo(infoType);
        return recordMapper.selectByExample(exa);
    }

    @Override
    public Map<Integer, SysAttachment> findByInfoMap(Long infoId, Byte infoType) {

        Map<Integer, SysAttachment> result = new HashMap<>();
        this.findByInfo(infoId, infoType).stream().forEach(item -> result.put(item.getFileType().intValue(), item));
        return result;
    }

    @Override
    public SysAttachment findById(Long id) {
        return recordMapper.selectByPrimaryKey(id);
    }

    @Override
    public int add(SysAttachment attachment) {
        return recordMapper.insertSelective(attachment);
    }

    @Override
    public int addOrUpdate(List<SysAttachment> attachments){

        if(attachments == null || attachments.isEmpty()) return 1; //不更新任何数据

        int result = 0 ;
        for(SysAttachment attachment : attachments){

            if(attachment.getId() == null){ //新增
                result += this.add(attachment);
            }
            //更新
            SysAttachment updateRecord = new SysAttachment();
            updateRecord.setId(attachment.getId());
            updateRecord.setFilePath(attachment.getFilePath());
            result += recordMapper.updateByPrimaryKeySelective(updateRecord);
        }
        return result;

    }

    @Override
    public int delByInfoId(Byte infoType, Long infoId) {

        SysAttachmentExample exa = new SysAttachmentExample();
        exa.createCriteria().andInfoTypeEqualTo(infoType).andInfoIdEqualTo(infoId);
        return recordMapper.deleteByExample(exa);
    }
}
